package com.jwx.mycar.utils;

import com.jwx.mycar.common.ServiceException;
import com.jwx.mycar.entity.po.Picture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class FileUtils {
	private final static Logger logger = LoggerFactory.getLogger(FileUtils.class);
	
	// 绝对路径
	private static String absolutePath = "";
	
	// 文件存放的目录	
	private static String UPLOAD_FOLDER = Paths.get("static", "upload").toString();
	
	/**
	 * 上传单个文件
	 * 最后文件存放路径为：static/upload/test.jpg
	 * @param is 文件流
	 * @param filename 文件名称
	 * @return
	 */
	public static Picture upload(MultipartFile file) {
		createDirIfNotExists();
		Picture picture = new Picture();
		String filename = file.getOriginalFilename();
		// 获得文件后缀名称
		String suffixName = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
		String rename = UUID.randomUUID().toString().replace("-", "") + "." + suffixName;
		picture.setPicName(file.getOriginalFilename());
		picture.setPicSize(file.getSize());
		try {
			byte[] bytes = file.getBytes();
			Path path = Paths.get(absolutePath, UPLOAD_FOLDER, rename);
			Files.write(path, bytes);
		} catch(IOException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException("文件处理失败");
		}
		picture.setPicPath(Paths.get(UPLOAD_FOLDER, rename).toString());
		return picture;
	}
	
	/**
	 * 删除文件
	 * @param filename 文件名称
	 * @return
	 */
	public static boolean delete(String filename) {
		if (StringUtils.isEmpty(filename)) return false;
		File file = new File(absolutePath, Paths.get(UPLOAD_FOLDER, filename).toString());
		if (file.exists()) {
			return file.delete();
		}
		return false;
	}
	
	/**
	 * 获取文件的绝对路径
	 */
	public static String getAbsolutePath(String filepath) {
		return Paths.get(absolutePath, filepath).toString();
	}
	
	/**
	 * 创建文件夹
	 */
	private static void createDirIfNotExists() {
		if (!absolutePath.isEmpty()) return;
		
		File file = null;
		try {
			file = new File(ResourceUtils.getURL("classpath:").getPath());
		} catch(FileNotFoundException e) {
			throw new RuntimeException("获取根目录失败，无法创建上传目录");
		}
		if (!file.exists()) {
			file = new File("");
		}
		absolutePath = file.getAbsolutePath();
		File upload = new File(absolutePath, UPLOAD_FOLDER);
		if (!upload.exists()) {
			upload.mkdirs();
		} 
	}
}
